<!--
  * 员工 表格 弹窗 选择框
  *
  * @Author:    zhoujk
  * @Date:      2025-02-09 15:05
-->
<template>
  <a-modal v-model:open="visible" :width="900" title="选择人员" @cancel="closeModal" @ok="onSelectUser">
    <a-form class="smart-query-form">
      <a-row class="smart-query-form-row">
        <a-form-item label="关键字" class="smart-query-form-item">
          <a-input style="width: 150px" v-model:value="params.keywords" placeholder="姓名/手机号/登录账号" />
        </a-form-item>
        <a-form-item label="部门" class="smart-query-form-item">
          <DepartTreeSelect style="width: 200px" ref="departTreeSelect" v-model:value="params.oDepartId" />
        </a-form-item>
        <a-form-item label="状态" class="smart-query-form-item">
          <SmartEnumSelect width="120px" v-model:value="params.status" enumName="ZZB_ENABLE_STATUS_ENUM" placeholder="请选择状态" />
        </a-form-item>
        <a-form-item class="smart-query-form-item smart-margin-left10">
          <a-button type="primary" @click="onSearch">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>
          <a-button @click="reset" class="smart-margin-left10">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
        </a-form-item>
      </a-row>
    </a-form>
    <a-table
      :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange, getCheckboxProps: getCheckboxProps }"
      :loading="tableLoading"
      size="small"
      :columns="columns"
      :data-source="tableData"
      :pagination="false"
      bordered
      rowKey="id"
      :scroll="{ y: 300 }"
    >
      <template #bodyCell="{ text, column }">
        <template v-if="column.dataIndex === 'status'">
          <a-tag :color="text ? 'processing' : 'error'">{{ text ? '启用' : '禁用' }}</a-tag>
        </template>

        <template v-if="column.dataIndex === 'sex'">
          <span>{{ $smartEnumPlugin.getDescByValue('ZZB_SEX_ENUM', text) }}</span>
        </template>
      </template>
    </a-table>
    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="params.pageSize"
        v-model:current="params.pageNo"
        v-model:pageSize="params.pageSize"
        :total="total"
        @change="queryUser"
        @showSizeChange="queryUser"
        :show-total="(total) => `共${total}条`"
      />
    </div>
  </a-modal>
</template>
<script setup>
  import { message } from 'ant-design-vue'
  import { computed, reactive, ref } from 'vue'
  import { userApi } from '/src/api/system/b-agent/user-api'
  import { PAGE_SIZE, PAGE_SIZE_OPTIONS } from '/src/constants/common-const'
  import DepartTreeSelect from '/src/components/system/b-agent/depart-tree-select/index.vue'
  import { smartSentry } from '/src/lib/smart-sentry'
  import SmartEnumSelect from '/src/components/framework/smart-enum-select/index.vue'

  // ----------------------- 以下是字段定义 emits props ---------------------
  const emits = defineEmits(['selectData'])
  defineExpose({
    showModal,
  })

  // ----------------------- modal  显示与隐藏 ---------------------

  const visible = ref(false)

  async function showModal(selectUserId) {
    originalRowKeyList.value = selectUserId || []
    selectedRowKeyList.value = selectUserId || []
    visible.value = true
    onSearch()
  }

  function closeModal() {
    Object.assign(params, defaultParams)
    selectedRowKeyList.value = []
    visible.value = false
  }

  // ----------------------- 员工查询表单与查询 ---------------------
  const tableLoading = ref(false)
  const departTreeSelect = ref()
  const total = ref()

  let defaultParams = {
    oDepartId: undefined,
    disabledFlag: undefined,
    keywords: undefined,
    searchCount: undefined,
    pageNo: 1,
    pageSize: PAGE_SIZE,
    sortItemList: undefined,
    showRoleFlag: false,
  }
  const params = reactive({ ...defaultParams })

  function reset() {
    Object.assign(params, defaultParams)
    queryUser()
  }

  function onSearch() {
    params.pageNo = 1
    queryUser()
  }

  async function queryUser() {
    tableLoading.value = true
    try {
      let res = await userApi.page(params)
      tableData.value = res.data
      total.value = res.total
    } catch (error) {
      smartSentry.captureError(error)
    } finally {
      tableLoading.value = false
    }
  }

  // ----------------------- 员工表格选择 ---------------------
  const originalRowKeyList = ref([])
  let selectedRowKeyList = ref([])
  const hasSelected = computed(() => selectedRowKeyList.value.length !== originalRowKeyList.value.length)

  function onSelectChange(selectedRowKeys) {
    selectedRowKeyList.value = selectedRowKeys
  }

  function onSelectUser() {
    if (!hasSelected.value) {
      message.warning('请选择角色人员')
      return
    }
    // 过滤出新选择的人员id
    const newUserIdList = selectedRowKeyList.value.filter((id) => !originalRowKeyList.value.includes(id))
    emits('selectData', newUserIdList)
    closeModal()
  }

  function getCheckboxProps(record) {
    return {
      // 角色员工列表的添加员工弹窗中 禁止添加选择已存在该角色的员工
      disabled: originalRowKeyList.value.includes(record.id),
    }
  }

  // ----------------------- 员工表格渲染 ---------------------
  const tableData = ref([])
  //字段
  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
    },
    {
      title: '性别',
      dataIndex: 'sex',
    },
    {
      title: '登录账号',
      dataIndex: 'no',
    },
    {
      title: '状态',
      dataIndex: 'status',
    },
  ]
</script>
